#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import bs4

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.keys import Keys

url = r'https://www.taobao.com'
kw = "mac键盘膜"   # 搜索关键字
title = 'iBrave'  # 搜索页面宝贝标题
color = '旧款pro13.3' # 款式

options = webdriver.ChromeOptions()
if False:
    options.headless = True
headers = {
    'User-Agent': 'user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36',
    'Accept-Language': 'zh-CN,zh;q=0.1'
}
cap = DesiredCapabilities.CHROME.copy()
for key, value in headers.items():
    cap['chorme.page.customHeaders.%s' % key] = value
driver = webdriver.Chrome(options=options, desired_capabilities=cap)
driver.get(url)

# 尝试登录
wait = WebDriverWait(driver, 10)
wait.until(expected_conditions.element_to_be_clickable((By.CLASS_NAME, 'member')))
button = driver.find_element_by_class_name('btn-login')
button.click()
driver.implicitly_wait(10)

n = driver.window_handles
driver.switch_to.window(n[1]) # switch to new window

# 切换登录方式（失败）
# driver.implicitly_wait(3)
# switch = driver.find_element_by_id('J_Static2Quick')
# switch.click()

# 保存cookie
# import pickle, pathlib
# pklPath = pathlib.Path('cookies.pkl')
# if pklPath.exists():
#     with open(pklPath, 'rb') as fo:
#         cookies = pickle.load(fo)
#     for cookie in cookies:
#         try:
#             driver.add_cookie(cookie)
#         except:
#             pass
# else:
#     cookies = driver.get_cookies()
#     with open(pklPath, 'wb') as fo:
#         pickle.dump(cookies, fo)

wait = WebDriverWait(driver, 60)  # 等待扫码登录

# 下载二维码（失败）
# import bs4
# import urllib.request as ur
# soup = bs4.BeautifulSoup(driver.page_source, "lxml")
# a = soup.find('div', {'class': 'qrcode-img'})
# print(a, a.img)
# ur.urlretrieve(a.img['src'], 'qrcode.png')

# 设置显示等待
wait = WebDriverWait(driver, 5)
wait.until(expected_conditions.presence_of_element_located((By.CLASS_NAME, 'search-combobox-input-wrap')))
search = driver.find_element_by_class_name('search-combobox-input')
search.send_keys(kw)
search.send_keys(Keys.ENTER)

link = driver.find_element_by_partial_link_text(title)
link.click()

wait = WebDriverWait(driver, 3)
n = driver.window_handles
driver.switch_to.window(n[2]) # switch to new window
wait = WebDriverWait(driver, 5)
wait.until(expected_conditions.presence_of_element_located((By.ID, 'detail')))
link = driver.find_element_by_partial_link_text(color)
link.click()

button = driver.find_element_by_class_name('tb-btn-buy.tb-btn-sku')
button.click()

wait = WebDriverWait(driver, 5)
wait.until(expected_conditions.presence_of_element_located((By.ID, 'submitOrderPC_1')))

button = driver.find_element_by_class_name('go-btn')
button.click()

password = driver.find_element_by_id('payPassword_rsainput')
password.send_keys('hangzhou2008')
button = driver.find_element_by_class_name('ui-button.ui-button-lblue')
# button.click()

